
----------------------------------------------------------------
--- Copyright：  迷你玩-海马
--- Description：进度保存到文件帮助模块
---    将一个对象（table-string）定期写到文件file中去
---    主要用来记录扫描进度，比如从扫描uin，从1到1000000000，
---    每60秒save一下，下次可以从断点继续扫描
----------------------------------------------------------------

--- 接口:
---  1 load 读取进度   (返回进度table)
---  2 save 存储进度

-- 文件名例子
-- local file_name_ = "./logs/scan_sync_" .. ns_config.doing_name .. '_' .. ngx.worker.id() .. ".txt"

----------------------------------------------------------------

local require    = require    
local setmetatable = setmetatable

----数据变量----
local uu         = require("modules.commhm.utils");
local log        = require("modules.commhm.log");


-- 时间缓存类 cache
local _M = { _VERSION = '0.12.1' }
local mt = { __index = _M }


function _M:new( filename_, time_interval_ )
	log.debug( log.fast() and "call CProgressMgr:new, time_interval_=" .. (time_interval_ or 60) );

	local ins_ = {
		last_save_time    = uu.now(),
		time_interval     = time_interval_ or 60,
		filename          = filename_,             --存储的完整路径
	};
    return setmetatable(ins_, mt);
end


-------------------------------------------------
-- flash_time后，下次save会立即存盘
function _M:flash_time()
	self.last_save_time = 0
end


-- 设置缓存table
function _M:save(data_)
	if  data_ then
		local now_ = uu.now()
		if  now_ - self.last_save_time > self.time_interval then
			self.last_save_time = now_
			-- save file
			if  self.filename then
				uu.save_table_file( self.filename, data_ )
			end
		end
	end
end


-- 加载缓存table
function  _M:load()
	if  self.filename and uu.file_exist( self.filename ) then
		return uu.read_table_file( self.filename )
	end
	return nil
end



return _M;
